package com.hubu.controller;

import com.hubu.config.WebAppConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @Author xiedi
 * @Date: 2022/11/6
 */
@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    private WebAppConfig appConfig;
    //文件下载相关代码
    @GetMapping(value = "/download/{fileName}")
    public String downloadImage(@PathVariable("fileName")String fileName, HttpServletResponse response) {
        String filePath = appConfig.getLocation() ;
        String fileUrl = filePath+ File.separator + fileName;
        String[] arr = fileName.split("\\.");
        String suffix = arr[1];
        File file = new File(fileUrl);

        if (file.exists()) {
            //response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition","attachment;fileName=" + fileName);// 设置文件名
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                if("csv".equalsIgnoreCase(suffix)){
                    //加上UTF-8文件的标识字符,避免乱码
                    os.write(new   byte []{( byte ) 0xEF ,( byte ) 0xBB ,( byte ) 0xBF });
                }
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {

                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }
}
